package com.bms.cfcmms.service;

import com.bms.cfcmms.dao.MenuDao;
import com.bms.cfcmms.dao.ModuleDao;
import com.bms.cfcmms.model.system.module.Module;
import com.bms.cfcmms.model.viewsetting.Menu;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;

/**
 * Created by carl on 2016/5/12.
 */
@Service
public class MenuService {

    @Resource
    private MenuDao menuDao;

    @Resource
    private ModuleDao moduleDao;

    /**
     * 获取所有的菜单.
     *
     * @return 所有菜单
     */
    public List<Menu> queryAllMenu() {
        Module module = moduleDao.queryForObjectByName(Menu.class.getSimpleName());
        List<Menu> results = menuDao.findMenuByPropertyAllSort(module, "orderId", "ASC",
                "pid", null);

        putModulInfoToMenu(null, module, results);
        return results;
    }

    private void putModulInfoToMenu(Menu parent, Module module, List<Menu> results) {
        if (parent != null && !results.isEmpty()) {
            parent.setMenus(results);
        }
        for (Menu menus : results) {
            Module menuModule = menus.getModule();
            if (menuModule != null) {
                if (menuModule.getModuleId() != null) {
                    menuModule.setModuleName(Module.class.getSimpleName());
                    menuModule.setPrimaryKey(Module.PRIMARY_KEY);
                    Module moduleObje = moduleDao.queryForObjectById(menuModule.getModuleId(), menuModule);
                    menus.setModule(moduleObje);
                }
            } else {
                List<Menu> subMenus = menuDao.findMenuByPropertyAllSort(module, "orderId",
                        "ASC", "pid", menus.getId());
                putModulInfoToMenu(menus, module, subMenus);
            }
        }
    }
}
